package cn.stylefeng.guns.utils.douyin;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.manager.entity.FlowOrder;
import cn.stylefeng.guns.modular.manager.entity.FlowPayInfo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class DouyinHttpUtil {


    public static final String URL_GET_DOUYIN_SESSION_KEY=DouyinConfig.URI_GET_SESSION_TOKEN;

    public static final String URL_DOUYIN_PRE_PAY=DouyinConfig.URL_DOUYIN_PRE_PAY;

    public static final String PAY_RESULT_CALLBACK_URL = DouyinConfig.PAY_CALL_BACK_HOST+DouyinConfig.CALLBACK_DOUYIN_PAY;

    /**
     * 获取抖音用户手机号码
     *
     * @param encryptedData 加密数据
     * @param code          代码
     * @param iv            iv
     * @return {@link DouyinResPhone }
     */
    public static DouyinResPhone getDouyinUserPhone(String encryptedData, String code, String iv){


        /**
         {
         "appid": "tt0fb3790e908cc20101",
         "secret": "9ca136cc9c38dc0c185fd576273938f8e3857ea1",
         "anonymous_code": "",
         "code": "0qL2TlxkmwBtGX85W2QFCfPpUq2oPICroxN7otzgzKLbnfYE_2ApBVaHAB9wQ1mzXZptWU-M4S4uT59uElzI-V8K_0RKKDRT2_uf0gCyA3DlRt2wujMXDNsDE-k"
         }
         * */

        GetSessionTokenQo qo=new GetSessionTokenQo();
        qo.setAppid(DouyinConfig.APPID);
        qo.setSecret(DouyinConfig.SECRET);
        qo.setAnonymous_code("");
        qo.setCode(code);

        String json = JSON.toJSONString(qo);

        //调用接口,获取sessionKey
        String result = HttpRequest.post(URL_GET_DOUYIN_SESSION_KEY)
                .header("content-type", "application/json")
                .body(json)
                .timeout(200000)
                .execute()
                .body();

        log.info("getDouyinPhone,result:"+result);


        DouyinResSessionToken sessionKey=JSON.parseObject(result,DouyinResSessionToken.class);

        String decrypt = null;
        try {
            //解密得到明文手机号码
            decrypt = Decrypt.decrypt(encryptedData, sessionKey.getData().getSession_key(), iv);
        } catch (Exception e) {
            log.error("getDouyinPhone,解密出现异常:"+e);
        }
        if(decrypt==null){
            return null;
        }
        else {
            DouyinResPhone phone =JSON.parseObject(decrypt,DouyinResPhone.class);
            phone.setOpenid(sessionKey.getData().getOpenid());
            phone.setUnionid(sessionKey.getData().getUnionid());
            return phone;
        }
    }

    /**
     * 预付款
     *
     * @param flowOrder 订单信息
     * @param payInfo   付款信息
     * @param extra     额外
     * @return {@link DouyinPrePayRes }
     */
    public static DouyinPrePayRes prePay(FlowOrder flowOrder,FlowPayInfo payInfo,String extra){


        DouyinPrePayQo qo=new DouyinPrePayQo();
        qo.setApp_id(DouyinConfig.APPID);
        qo.setOut_order_no(payInfo.getPayCode());
        qo.setSubject(extra);
        qo.setBody(flowOrder.getOrderId()+"");
        qo.setValid_time(170000);
        qo.setCp_extra(extra);


        Double value = payInfo.getMoneys().doubleValue() * 100.0D;
        qo.setTotal_amount(value.intValue());

        qo.setNotify_url(PAY_RESULT_CALLBACK_URL);

        /**


         {
         "app_id": "tt07e3715e98c9aac0",
         "out_order_no": "out_order_no_1",
         "total_amount": 12800,
         "subject": "测试商品",
         "body": "测试商品",
         "valid_time": 180,
         "sign": "d716027b7b5a91a3319a061d818cc9cc",
         "cp_extra": "一些附加信息",
         "notify_url": "https://api.iiyyeixin.com/Notify/bytedancePay"
         }
         *
         * */



        Map<String, Object> testCase = new HashMap<String, Object>() {
            {
                put("app_id", qo.getApp_id());
                put("out_order_no", qo.getOut_order_no());
                put("total_amount", qo.getTotal_amount());
                put("subject", qo.getSubject());
                put("body", qo.getBody());
                put("valid_time", qo.getValid_time());
                put("notify_url", qo.getNotify_url());
                //put("disable_msg", 0);
                //put("msg_page", "pages/user/orderDetail/orderDetail?id=997979879879879879");
                //put("sign", "edc608b160a1be3de0xxxxxx");
            }
        };

        String testCaseJson = JSON.toJSONString(testCase);
        log.info("prePay,testCaseJson:"+testCaseJson);


        String sign = Sign.requestSign(testCase);
        log.info("prePay,加签:"+sign);
        qo.setSign(sign);


        testCase.put("sign",sign);


        String json = JSON.toJSONString(testCase);
        log.info("prePay,json:"+json);

        //调用接口,获取预支付订单信息
        String result = HttpRequest.post(URL_DOUYIN_PRE_PAY)
                .header("content-type", "application/json")
                .body(json)
                .timeout(200000)
                .execute()
                .body();

        DouyinPrePayRes res= JSON.parseObject(result,DouyinPrePayRes.class);
        log.info("prePay,预支付结果:"+res);

        return res;
    }
}
